package com.free4inno.knowledgems.controller;

import com.free4inno.knowledgems.dao.GroupInfoDao;
import com.free4inno.knowledgems.dao.LabelInfoDao;
import com.free4inno.knowledgems.dao.ResourceDao;
import com.free4inno.knowledgems.dao.UserDao;
import com.free4inno.knowledgems.domain.*;
import com.free4inno.knowledgems.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Author HUYUZHU.
 * Date 2021/1/3 17:08.
 */

@Slf4j
@Controller
@RequestMapping("/myresource")
public class MyResourceController {

    @Autowired
    private ResourceDao resourceDao;

    @Autowired
    private LabelInfoDao labelInfoDao;

    @Autowired
    private GroupInfoDao groupInfoDao;

    @Autowired
    private UserDao userDao;

    //每一页的结果显示数量
    int size = 10;

//    //导航栏”我的“按钮
//    @RequestMapping("")
//    public String myResource(HttpSession session, Map param) {
//        int userId = (int) session.getAttribute(Constants.USER_ID);
//        //TODO 111
//        String userName = (String) session.getAttribute(Constants.USER_NAME);
//        param.put("userId", userId);
//        param.put("userName", userName);
//        return "/resource/myresource";
//    }

    //点击名字跳转至用户发布的资源列表
    @RequestMapping("")
    public String otherResource(@RequestParam("userId") int userId,
                                Map param, HttpSession session) {
        //按照userId寻找到userName
        //TODO 没有错误处理机制（userId表中没有的情况）
        log.info(this.getClass().getName()+"----in----"+"(otherResource)"+"----"+session.getAttribute(Constants.USER_ID));
        User user = userDao.findById(userId).orElse(new User());
        String userName = user.getRealName();
        param.put("userId", userId);
        param.put("userName", userName);
        log.info(this.getClass().getName()+"----out----"+"跳转至用户发布的资源列表"+"----"+session.getAttribute(Constants.USER_ID));
        return "/resource/myresource";
    }

    @RequestMapping("/queryMyResourceData")
    public String queryMyResourceData(@RequestParam("userId") int userId, @RequestParam("userName") String userName,
                                      @RequestParam("page") int page, Map param, HttpSession session) {
        log.info(this.getClass().getName()+"----in----"+"(queryMyResourceData)"+"----"+session.getAttribute(Constants.USER_ID));
        //按照userId寻找到userEmail
        User user = userDao.findById(userId).orElse(new User());
        String userEmail = user.getMail();
        //按照userId查找，按照createTime倒序排列，分页
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<Resource> resourcePage = resourceDao.findAllByUserId(pageable, userId);
        long resourceNum = resourcePage.getTotalElements();
        long pageSize;
        //pageSize
        if (resourceNum % 10 == 0) {
            pageSize = resourceNum / 10;
        } else {
            pageSize = resourceNum / 10 + 1;
        }

        //将所有数据返回为List
        List<Resource> resourceList = resourcePage.getContent();

        // 1. build 2 hash set to De-duplication : label, group
        HashSet<Integer> labelsId = new HashSet<>();
        HashSet<Integer> groupsId = new HashSet<>();
        for (Resource resource : resourceList) {
            // 1.1. label
            if (resource.getLabelId() != null && !resource.getLabelId().equals("")) {
                String[] label = resource.getLabelId().split(",|，");
                for (String s : label) {
                    int labelId = (s == "" ? 0 : Integer.parseInt(s));
                    labelsId.add(labelId);
                }
            }
            // 1.2. group
            if (resource.getGroupId() != null && !resource.getGroupId().equals("")) {
                String[] group = resource.getGroupId().split(",|，");
                for (String s : group) {
                    int groupId = (s == "" ? 0 : Integer.parseInt(s));
                    groupsId.add(groupId);
                }
            }
        }

        // 2. build 2 hash map to save all string names
        HashMap<Integer, String> labelsName = new HashMap<>();
        HashMap<Integer, String> groupsName = new HashMap<>();
        // 2.1. label
        for (Integer labelId : labelsId){
            LabelInfo labelInfo = labelInfoDao.findById(labelId).orElse(new LabelInfo());
            if (labelInfo.getLabelName() != null) {
                String ln = labelInfo.getLabelName();
                labelsName.put(labelId, ln);
            } else {
                labelsName.put(labelId, "未知标签" + labelId);
            }
        }
        // 2.2. group
        for (Integer groupId : groupsId){
            GroupInfo groupInfo = groupInfoDao.findById(groupId).orElse(new GroupInfo());
            if (groupInfo.getGroupName() != null) {
                String gn = groupInfo.getGroupName();
                groupsName.put(groupId, gn);
            } else {
                groupsName.put(groupId, "未知群组" + groupId);
            }
        }

        // 3. use names in map, reduce interactions with DB
        resourceList.forEach(resource -> {
            String text = resource.getText();
            String title = resource.getTitle();
            resource.setText(text.replaceAll("<.*?>", ""));
            resource.setTitle(title.replaceAll("<.*?>", ""));
            //取作者名
            resource.setUserName(userName);
            //取群组名
            String groupNames = "";
            if (resource.getGroupId() != null && !resource.getGroupId().equals("")) {
                List<String> groupIdList = Arrays.asList(resource.getGroupId().split(",|，"));
                for (String s : groupIdList) {
                    int groupId = (s == "" ? 0 : Integer.parseInt(s));
                    groupNames = groupNames + "," + groupsName.get(groupId);
                }
                groupNames = groupNames.substring(1);
            } else {
                groupNames = "该资源无群组";
            }
            resource.setGroupName(groupNames);
            //取标签名
            String labelNames = "";
            if (resource.getLabelId() != null && !resource.getLabelId().equals("")) {
                List<String> labelIdList = Arrays.asList(resource.getLabelId().split(",|，"));
                for (String item : labelIdList) {
                    int labelId = (item == "" ? 0 : Integer.parseInt(item));
                    labelNames = labelNames + "," + labelsName.get(labelId);
                }
                labelNames = labelNames.substring(1);
            } else {
                labelNames = "该资源无标签";
            }
            resource.setLabelName(labelNames);
        });
        param.put("resourceList", resourceList);
        param.put("resourceNum", resourceNum);
        param.put("pageSize", pageSize);
        param.put("userName", userName);
        param.put("userEmail", userEmail);
        log.info(this.getClass().getName()+"----out----"+"返回用户详细资源数据"+"----"+session.getAttribute(Constants.USER_ID));
        return "/resource/_result";
    }
}
